package com.easylinkin.linkappapi.machinery.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.easylinkin.linkappapi.annotation.CommonOperateLogAnnotate;
import com.easylinkin.linkappapi.building.entity.Building;
import com.easylinkin.linkappapi.building.service.BuildingService;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.machinery.dto.MachineryRecordDTO;
import com.easylinkin.linkappapi.machinery.dto.MachineryUserLinkDTO;
import com.easylinkin.linkappapi.machinery.entity.MachineryParameter;
import com.easylinkin.linkappapi.machinery.entity.MachineryRecord;
import com.easylinkin.linkappapi.machinery.service.MachineryRecordService;
import com.easylinkin.linkappapi.machinery.vo.MachineryDeviceVo;
import com.easylinkin.linkappapi.operatelog.LogHelper;
import com.easylinkin.linkappapi.operatelog.constant.LogConstant.LogModule;
import com.easylinkin.linkappapi.operatelog.constant.LogConstant.LogOperateType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import jodd.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.annotation.Resource;

/**
 * @author: kan yuanfeng
 * @Date: 2020/11/04 11:42
 * @Description: 电子档案管理
 */
@RestController
@RequestMapping("machineryRecord")
@Api(tags = "电子档案管理")
public class MachineryRecordController {
  
  @Autowired
  private MachineryRecordService machineryRecordService;
  @Resource
  private BuildingService buildingService;

  /**
   * @Description: 查询设备特性参数
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @GetMapping("machineryParameter/{code}")
  @ApiOperation("查询设备特性参数")
  public RestMessage getParameter(@PathVariable("code") String code){
    //参数验证
    Assert.notNull(code,"型号不能为空");
    List<MachineryParameter> parameters = machineryRecordService.getParameter(code);
    return RestBuilders.successBuilder().data(parameters).build();
  }

  /**
   * @Description: 查询管理人员
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @GetMapping("machineryUser/{code}")
  @ApiOperation("查询设备特性参数")
  public RestMessage getUser(@PathVariable("code") String code, @RequestParam(value = "tenantId",required = false) String tenantId){
    //参数验证
    Assert.notNull(code,"型号不能为空");
    List<MachineryUserLinkDTO> parameters = machineryRecordService.getUser(code,tenantId);
    return RestBuilders.successBuilder().data(parameters).build();
  }

  /**
   * @Description: 增加电子档案
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PostMapping
  @ApiOperation("增加电子档案")
  public RestMessage insert(@RequestBody MachineryRecordDTO machineryRecordDTO){
    //参数验证
    machineryRecordService.insert(machineryRecordDTO);
    return RestBuilders.successBuilder().build();
  }

  /**
   * @Description: 删除电子档案（包含批量删除）
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @DeleteMapping
  @ApiOperation("删除电子档案（包含批量删除）")
  @CommonOperateLogAnnotate(module = LogModule.MACHINERY_MANAGEMENT, desc = "")
  public RestMessage delBatch(@RequestBody MachineryRecord machineryRecord){
    Assert.notEmpty(machineryRecord.getIds(),"id不能为空");
    // 记录日志详情
    List<String> names = new ArrayList<>();
    machineryRecord.getIds().forEach(p->{
      MachineryRecord machineryRecordById = machineryRecordService.getById(p);
      names.add(machineryRecordById.getName());
    });
    if(CollectionUtil.isNotEmpty(names)){
      LogHelper
          .setContent(LogOperateType.MACHINERY_RECORD_DELETE, StringUtil
              .join(names,","));
    }
    machineryRecordService.removeByIds(machineryRecord.getIds());
    //增加解除IOT设备绑定关系
    machineryRecordService.unbindIotDevice(machineryRecord.getIds());
    return RestBuilders.successBuilder().build();
  }

  /**
   * @Description: 编辑电子档案
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PutMapping
  @ApiOperation("编辑电子档案")
  @CommonOperateLogAnnotate(module = LogModule.MACHINERY_MANAGEMENT, desc = "")
  public RestMessage updateById(@RequestBody MachineryRecordDTO machineryRecordDTO){
    Assert.notNull(machineryRecordDTO.getId(),"id不能为空");
    // 记录日志详情
    MachineryRecord old = machineryRecordService.getById(machineryRecordDTO.getId());
    LogHelper.setContent(LogOperateType.MACHINERY_RECORD_UPDATE,old.getName());
    machineryRecordService.updateOne(machineryRecordDTO);
    return RestBuilders.successBuilder().build();
  }

  /**
   * @Description: 根据id查询电子档案详情
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @GetMapping("{id}")
  @ApiOperation("根据id查询电子档案详情")
  public RestMessage findById(@PathVariable("id")Integer id) {
    Assert.notNull(id,"id不能为空");
    MachineryRecord machineryRecord = machineryRecordService.getById(id);
    List<MachineryParameter> srcParameters = new ArrayList<>();
    if (machineryRecord != null) {
      srcParameters = machineryRecordService.getParameter(machineryRecord.getTypeCode());
    }
    //参数转换
    MachineryRecordDTO machineryRecordDTO = BeanUtil
        .toBean(machineryRecord, MachineryRecordDTO.class);
    if (machineryRecordDTO != null) {
      String parameter = machineryRecordDTO.getParameter();
      List<MachineryParameter> parameters = new ArrayList<>();
      if (StringUtils.isNotBlank(parameter)) {
        parameters = JSONUtil.toList(parameter, MachineryParameter.class);
      }
      List<MachineryParameter> finalParameters = parameters;
      srcParameters.forEach(s -> {
        List<MachineryParameter> parameterList = finalParameters.stream()
                .filter(p -> s.getKey().equals(p.getKey()))
                .collect(Collectors.toList());
        if (parameterList.size() > 0) {
          s.setValue(parameterList.get(0).getValue());
        }
      });
      machineryRecordDTO.setMachineryParameterList(srcParameters);
      machineryRecordDTO.setBuilding(buildingService.findBuildingWithFloors(machineryRecordDTO.getBuildingId()));
    }




    return RestBuilders.successBuilder().data(machineryRecordDTO).build();
  }

  /**
   * 扩展不选择设备，也要返回设备信息
   * @param id
   * @param typeCode 设备类型
   * @return
   */
  @GetMapping("/{id}/{typeCode}")
  @ApiOperation("根据id查询电子档案详情")
  public RestMessage findById(@PathVariable("id")Integer id,@PathVariable("typeCode")String typeCode) {
    if (id.intValue() != -1){
      return findById(id);
    }

    MachineryRecord machineryRecord = new MachineryRecord();
    //参数转换
    MachineryRecordDTO machineryRecordDTO = BeanUtil
            .toBean(machineryRecord, MachineryRecordDTO.class);
    Building building = new Building();
    if(StringUtils.isNotBlank(typeCode)){

      List<MachineryParameter> srcParameters = machineryRecordService.getParameter(typeCode);

      String parameter = machineryRecordDTO.getParameter();
      List<MachineryParameter> parameters = new ArrayList<>();
      if (StringUtils.isNotBlank(parameter)){
        parameters = JSONUtil.toList(parameter, MachineryParameter.class);
      }
      List<MachineryParameter> finalParameters = parameters;
      srcParameters.forEach(s ->{
        List<MachineryParameter> parameterList = finalParameters.stream()
                .filter(p -> s.getKey().equals(p.getKey()))
                .collect(Collectors.toList());
        if (parameterList.size() > 0){
          s.setValue(parameterList.get(0).getValue());
        }
      });
      machineryRecordDTO.setMachineryParameterList(srcParameters);
      if(machineryRecordDTO.getBuildingId() != null){
        buildingService.findBuildingWithFloors(machineryRecordDTO.getBuildingId());
      }
    }

    machineryRecordDTO.setBuilding(building);
    return RestBuilders.successBuilder().data(machineryRecordDTO).build();
  }

  /**
   * @Description: 根据条件，分页(不分页)查询
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PostMapping("list")
  @ApiOperation("根据条件，分页(不分页)查询")
  public RestMessage queryListByPage(@RequestBody RequestModel<MachineryRecord> requestModel, @RequestParam(value = "enterpriseFlag", required = false) Boolean enterpriseFlag) {
    Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
    Assert.notNull(requestModel.getPage(), "page 不能为空");
    IPage<MachineryRecord> record = machineryRecordService.queryListByPage(requestModel, enterpriseFlag);
    return RestBuilders.successBuilder().data(record).build();
  }

  /**
   * @Description: 根据条件，查询
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PostMapping("app/list")
  @ApiOperation("根据条件，查询")
  public RestMessage queryAppList(@RequestBody MachineryRecord machineryRecord){
    Map<String,List<MachineryRecord>> machineryRecords =  machineryRecordService.queryAppList(machineryRecord);
    return RestBuilders.successBuilder().data(machineryRecords).build();
  }

  /**
   * @Description: 获取电子档案IOT设备关联数据
   * @author zhengwen
   * @date 2022/08/05 11:42
   */
  @PostMapping("/iotDeviceRefData")
  @ApiOperation("获取电子档案IOT设备关联数据")
  public RestMessage iotDeviceRefData(@RequestBody MachineryDeviceVo machineryDeviceVo){

    return machineryRecordService.iotDeviceRefData(machineryDeviceVo);
  }

  /**
   * @Description: 关联绑定IOT设备
   * @author zhengwen
   * @date 2022/08/05 11:42
   */
  @PostMapping("/bindIotDevices")
  @ApiOperation("关联绑定IOT设备")
  public RestMessage bindIotDevices(@RequestBody MachineryDeviceVo machineryDeviceVo){

    return machineryRecordService.bindIotDevices(machineryDeviceVo);
  }
}

